package org.csu.sei.util.interceptor;

import com.alibaba.fastjson.JSONObject;
import org.csu.sei.entity.User;
import org.csu.sei.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.csu.sei.util.TokenUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TEACHERInterceptor implements HandlerInterceptor {

    private static final Logger logger= LoggerFactory.getLogger(TEACHERInterceptor.class);

    @Resource
    private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception{
        if(request.getMethod().equals("OPTIONS")){
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        response.setCharacterEncoding("utf-8");
        String token = request.getHeader("token");
//        //默认通过拦截
//        if(true) {
//            return true;
//        }
        //token内有内容
        if(token != null){
            boolean result = TokenUtil.verify(token);
            User user = TokenUtil.getUserData(token);
            User usercheck = userService.getById(user.getId());

            if (usercheck == null){
                result = false;
            }

            //验证通过,否则进入下面拒绝流程
            if(result){
                //权限验证
                if (usercheck.getRole() <= 2){
                    //后面调整为日志
                    logger.info("通过拦截器");
                    //通过拦截器
                    return true;
                }
            }
        }

        //拒绝流程
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try{
            JSONObject json = new JSONObject();
            //这里要商量用户未登录的code
            json.put("msg","token verify fail");
            json.put("code","403");
            response.getWriter().append(json.toJSONString());
            //后面调整为日志
            logger.info("认证失败，未通过拦截器");
        }catch (Exception e){
            e.printStackTrace();
            response.sendError(500);//服务器问题
            return false;
        }
        return false;
    }
}

